<?php

namespace App\Model;

use App\Helpers\ConfigUtil;
use App\Helpers\PayUtil;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 *  充值订单
 */
class PayOrder extends Model
{
    protected $table = 'pay_order';

    protected $fillable = [
        "user_id",  "status", "total_amount", "send_coin", "finished_at", "recharge_coin", "channel", "order_id"
    ];

    //待支付
    const STATUS_ING = 0;
    //支付成功
    const STATUS_OK = 1;
    //支付超时
    const STATUS_EXP = 2;
    //支付失败
    const STATUS_FAIL = 3;
    //标记其他
    const STATUS_EXTRA = 4;
    const STATUS = [
        self::STATUS_ING => '待支付',
        self::STATUS_OK => '支付成功',
        self::STATUS_EXP => '支付超时',
        self::STATUS_FAIL => '支付失败',
        self::STATUS_EXTRA => '未知状态'
    ];

    //微信支付
    const CHANNEL_WX = 'wechat';
    //支付宝
    const CHANNEL_ALI = 'alipay';
    //苹果内购
    const CHANNEL_APPLE = 'apple';
    //杉德微信
    const CHANNEL_SAND_WX = 'sd_wechat';
    //杉德支付宝
    const CHANNEL_SAND_ALI = 'sd_alipay';
    const CHANNEL = [
        self::CHANNEL_WX => '微信支付',
        self::CHANNEL_ALI => '支付宝',
        self::CHANNEL_SAND_WX => '微信（杉德）',
        self::CHANNEL_SAND_ALI => '支付宝（杉德）',
        self::CHANNEL_APPLE => '苹果内购'
    ];

    //订单类型
    const TYPE_RECHARGE = 1;
    const TYPE_FIRST_SEND = 2;
    const TYPE_RECHARGE_SEND = 3;
    const TYPE = [
        self::TYPE_RECHARGE => '充值',
        self::TYPE_FIRST_SEND => '首充赠送',
        self::TYPE_RECHARGE_SEND => '超值赠送'
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function subject()
    {
        return $this->belongsTo(SettingRecharge::class, 'subject_id', 'id');
    }

    static function getRechargeCount($startTime = '', $endTime = '', $channel = '')
    {
        if (!$channel) {
            $where = [
                ['status', self::STATUS_OK],
            ];
            if ($startTime) $where[] = ['created_at', '>=', $startTime];
            if ($endTime) $where[] = ['created_at', '<', $endTime];
            $query = self::where($where);
        } else {
            $table = 'pay_order';
            $where = [
                [$table . '.status', self::STATUS_OK],
            ];
            if ($startTime) $where[] = [$table . '.created_at', '>=', $startTime];
            if ($endTime) $where[] = [$table . '.created_at', '<', $endTime];
            $query = DB::table($table)->join('user', function ($join) use ($where, $channel, $table) {
                $where[] = ['user.channel', $channel];
                $join->on('user.id', '=', $table . '.user_id')->where($where);
            });
        }
        $data = $query->select(DB::raw('count(distinct user_id) as ctn'))->first();
        return $data && $data->ctn ? $data->ctn : 0;
    }

    /**
     * 新增充值用户
     */
    static function getNewRechargeCount($startTime = '', $endTime = '', $channel = '', $type = 'user')
    {
        $table = 'pay_order';
        $Utable = 'user';
        $where = [
            [$table . '.status', self::STATUS_OK],
        ];
        $channel && $where[] = ['user.channel', $channel];
        $startTime && $where[] = [$table . '.created_at', '>=', $startTime];
        $endTime && $where[] = [$table . '.created_at', '<', $endTime];
        $startTime && $where[] = [$Utable . '.created_at', '>=', $startTime];
        $endTime && $where[] = [$Utable . '.created_at', '<', $endTime];
        $query = DB::table($table)->join('user', function ($join) use ($table) {
            $join->on('user.id', '=', $table . '.user_id');
        })->where($where);
        if ($type == 'user') $data = $query->select(DB::raw('count(distinct user_id) as ctn'))->first();
        else $data = $query->select(DB::raw('sum(recharge_coin) as ctn'))->first();
        return $data && $data->ctn ? $data->ctn : 0;
    }

    static function getTotal($start = '', $type = 'rmb')
    {
        !$start &&  $start = date('Y-m-d');
        $where = [
            ['status', self::STATUS_OK],
        ];
        if ($start) $where[] = ['finished_at', '>=', $start];
        if ($type == 'rmb') {
            $data = self::where($where)->select(DB::raw('sum(total_amount) as rmb'))->first();
            return $data ? $data->rmb / 100 : 0;
        } elseif ($type == 'count') {
            return self::where($where)->count();
        } elseif ($type == 'coin') {
            $data1 = self::where($where)->select(DB::raw('sum(recharge_coin) as coin'))->first();
            $data2 = self::where($where)->select(DB::raw('sum(send_coin) as send_coin'))->first();
            return $data1 && $data2  ? ($data1->coin + $data2->send_coin) : 0;
        }
    }
}
